package com.simpletour.qa.gateway.util;

/**
 * 为输出API DOC格式化json
 * @author zhaohw
 * @date 2018-06-22 14:45
 */
public class JsonFormatUtil {

    public static String format(String jsonStr) {
        int level = 0;
        StringBuilder jsonForMatStr = new StringBuilder();
        for(int i=0;i<jsonStr.length();i++){
            char c = jsonStr.charAt(i);
            if(level>0&&'\n'==jsonForMatStr.charAt(jsonForMatStr.length()-1)){
                jsonForMatStr.append(getLevelStr(level));
            }
            switch (c) {
                case '{':
                case '[':
                    jsonForMatStr.append(c).append("\n");
                    level++;
                    break;
                case ',':
                    char d = jsonStr.charAt(i-1);
                    if(d == '"' || d == ']'){
                        jsonForMatStr.append(c).append("\n");
                    } else {
                        jsonForMatStr.append(c).append("\n");
                    }
                    break;
                case '}':
                case ']':
                    jsonForMatStr.append("\n");
                    level--;
                    jsonForMatStr.append(getLevelStr(level));
                    jsonForMatStr.append(c);
                    break;
                default:
                    jsonForMatStr.append(c);
                    break;
            }
        }
        return jsonForMatStr.toString();
    }

    private static String getLevelStr(int level){
        StringBuilder levelStr = new StringBuilder();
        for(int levelI = 0;levelI<level ; levelI++){
            levelStr.append("\t");
        }
        return levelStr.toString();
    }

    public static void main(String[] args) {
        String s = "{\"code\":0,\"error\":\"success\",\"msg\":\"操作成功\",\"result\":\"eyJhbGciOiJIUzUxMiIsInppcCI6IkRFRiJ9.eNpEi0sKwyAURffyxhKi8YPuoGsoGfgFS4xBDRZK9h5LB53dwz3nA68WQQEJ2BgyS4eJoAsTxvlgLF4s0ywQygBBrHWIvfepxnRsvuWzTDan76UbKMyI5FSKmSM4qy8PB0r85q6TH612Ke5DL3kb-FwR-PfxDzm_bgAAAP__.eVxcJ0sfFTCOvMEQTi-RbUSZWkLWSZNn3PN4G8dw5WDJCjgMz55Ad_Qcnlsx3oFxvkqNEHTSgS-IO5_TZsjO_Q\"}";
        System.out.println(format(s));
    }
}
